<template>
  <a-card :bordered="false">
    <!-- 操作按钮区域 -->
    <div class="table-operator" v-if="!disabled">
      <a-button @click="handleAdd" icon="plus" type="primary" size="small">新增</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :expandedRowKeys="expandedRowKeys"
        @change="handleTableChange"
        @expand="handleExpand"
        :defaultExpandAllRows="true"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }"
        v-bind="tableProps"
      >
        <span slot="action" slot-scope="text, record"  v-if="!disabled">
          <a-button @click="handleEdit(record)" size="small" icon="edit" />
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record)">
            <a-button size="small" icon="delete" />
          </a-popconfirm>
          <a-divider type="vertical" />
          <a-button size="small" icon="plus-square" @click="handleAddSub(record)" />
        </span>
      </a-table>
    </div>

    <category-modal
      ref="modalForm"
      @ok="modalFormOk"
      :projectId="projectId"
      :scoreStandardId="scoreStandardId"
      :standardType="standardType"
    />
  </a-card>
</template>

<script>
import { getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CategoryModal from './ChapterModal'
import { deleteAction } from '@/api/manage'

export default {
  name: 'ChapterListMini',
  mixins: [JeecgListMixin],
  components: {
    CategoryModal,
  },
  props: {
    projectId: {
      default: '',
    },
    scoreStandardId: {
      default: '',
    },
    standardType: {
      //指标类型（评分指标、价格指标
      default: '',
    },
    disabled:{
      default: false
    }
  },
  data() {
    return {
      description: '评分明细分类',
      // 表头
      columns: [
        {
          title: ' ',
          align: 'left',
          dataIndex: 'name',
        },
        // {
        //   title: '指标名称',
        //   align: 'left',
        //   dataIndex: 'indicatorName',
        // },
        // {
        //   title: '指标类型',
        //   align: 'left',
        //   dataIndex: 'indicatorType',
        // },
        // {
        //   title: '分值',
        //   align: 'left',
        //   dataIndex: 'score',
        // },
        //
        // {
        //   title: '评分',
        //   align: 'left',
        //   dataIndex: 'scoreValue',
        // },
        // {
        //   title: '最小分值',
        //   align: 'left',
        //   dataIndex: 'scoreMin',
        // },
        // {
        //   title: '最大分值',
        //   align: 'left',
        //   dataIndex: 'scoreMax',
        // },
        //
        // {
        //   title: '权重',
        //   align: 'left',
        //   dataIndex: 'weight',
        // },
        //
        // {
        //   title: '评审说明',
        //   align: 'left',
        //   dataIndex: 'description',
        // },
        {
          title: ' ',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/exTenderFile/scoreChapter/rootList',
        childList: '/exTenderFile/scoreChapter/childList',
        getChildListBatch: '/exTenderFile/scoreChapter/getChildListBatch',
        delete: '/exTenderFile/scoreChapter/delete',
        deleteBatch: '/exTenderFile/scoreChapter/deleteBatch',
        exportXlsUrl: '/exTenderFile/scoreChapter/exportXls',
        importExcelUrl: 'exTenderFile/scoreChapter/importExcel',
        treeList:'/exTenderFile/scoreChapter/treeList'
      },
      expandedRowKeys: [],
      hasChildrenField: 'hasChild',
      pidField: 'pid',
      dictOptions: {},
      subExpandedKeys: [],
      queryParam: {
        projectId: '',
        scoreStandardId: '',
        standardType: '',
      },
    }
  },
  watch: {
    scoreStandardId(newVal, oldVal) {
      this.loadData()
    },
  },
  computed: {
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        rowSelection: {
          selectedRowKeys: _this.selectedRowKeys,
          onChange: (selectedRowKeys) => (_this.selectedRowKeys = selectedRowKeys),
        },
      }
    },
  },
  methods: {
    loadData(arg) {
      if (this.scoreStandardId == '') {
        return
      }
      if (arg == 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      let params = this.getQueryParams()
      params.scoreStandardId = this.scoreStandardId
      params.standardType = this.standardType
      return new Promise((resolve) => {
        getAction(this.url.list, params)
          .then((res) => {
            if (res.success) {
              let result = res.result
              if (Number(result.total) > 0) {
                this.ipagination.total = Number(result.total)
                this.dataSource = this.getDataByResult(res.result.records)
                this.expandedRowKeys = res.result.records.map((e) => e.id)
                //update--begin--autor:lvdandan-----date:20201204------for：JT-31 删除成功后默认展开已展开信息
                return this.loadDataByExpandedRows(this.dataSource)
                //update--end--autor:lvdandan-----date:20201204------for：JT-31 删除成功后默认展开已展开信息
              } else {
                this.ipagination.total = 0
                this.dataSource = []
              }
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    treeList(){
      getAction(this.url.treeList, { sectionId: this.scoreStandardId})
        .then((res) => {
          if (res.success) {
            let result = res.result
            console.log(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    getDataByResult(result) {
      if (result && result.length > 0) {
        return result.map((item) => {
          //判断是否标记了带有子节点
          if (item[this.hasChildrenField] == '1') {
            let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true }
            item.children = [loadChild]
          }
          return item
        })
      }
    },
    handleExpand(expanded, record) {
      // 判断是否是展开状态
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        if (record.children.length > 0 && record.children[0].isLoading === true) {
          let params = this.getQueryParams() //查询条件
          params[this.pidField] = record.id
          getAction(this.url.childList, params).then((res) => {
            if (res.success) {
              if (res.result && res.result.length > 0) {
                record.children = this.getDataByResult(res.result)
                this.dataSource = [...this.dataSource]
              } else {
                record.children = ''
                record.hasChildrenField = '0'
              }
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      } else {
        let keyIndex = this.expandedRowKeys.indexOf(record.id)
        if (keyIndex >= 0) {
          this.expandedRowKeys.splice(keyIndex, 1)
        }
      }
    },
    initDictConfig() {},
    modalFormOk(formData, arr) {
      this.$emit('change',formData.newId,this.selectedRowKeys)
      this.selectedRowKeys = [formData.newId]
      if (!formData.id) {
        this.addOk(formData, arr)
      } else {
        this.editOk(formData, this.dataSource)
        this.dataSource = [...this.dataSource]
      }
    },
    editOk(formData, arr) {
      if (arr && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].id == formData.id) {
            arr[i] = formData
            break
          } else {
            this.editOk(formData, arr[i].children)
          }
        }
      }
    },
    async addOk(formData, arr) {
      if (!formData[this.pidField]) {
        this.loadData()
      } else {
        this.expandedRowKeys = []
        console.log('22222', arr)
        for (let i of arr) {
          await this.expandTreeNode(i)
        }
      }
    },
    expandTreeNode(nodeId) {
      return new Promise((resolve, reject) => {
        this.getFormDataById(nodeId, this.dataSource)
        let row = this.parentFormData
        this.expandedRowKeys.push(nodeId)
        let params = this.getQueryParams() //查询条件
        params[this.pidField] = nodeId
        getAction(this.url.childList, params).then((res) => {
          console.log('11111', res)
          if (res.success) {
            if (res.result && res.result.length > 0) {
              row.children = this.getDataByResult(res.result)
              this.dataSource = [...this.dataSource]
              resolve()
            } else {
              row.children = ''
              row.hasChildrenField = '0'
              reject()
            }
          } else {
            reject()
          }
        })
      })
    },
    getFormDataById(id, arr) {
      if (arr && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].id == id) {
            this.parentFormData = arr[i]
          } else {
            this.getFormDataById(id, arr[i].children)
          }
        }
      }
    },
    handleAddSub(record) {
      this.subExpandedKeys = []
      this.getExpandKeysByPid(record.id, this.dataSource, this.dataSource)
      this.$refs.modalForm.subExpandedKeys = this.subExpandedKeys
      this.$refs.modalForm.title = '添加子项'
      this.$refs.modalForm.edit({ pid: record.id })
      this.$refs.modalForm.disableSubmit = false
    },
    handleDelete: function (record) {
      let that = this
      deleteAction(that.url.delete, { id: record.id }).then((res) => {
        if (res.success) {
          //update--begin--autor:lvdandan-----date:20201204------for：JT-31 删除成功后默认展开已展开信息
          this.loadData()
          //update--end--autor:lvdandan-----date:20201204------for：JT-31 删除成功后默认展开已展开信息
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    // 添加子分类时获取所有父级id
    getExpandKeysByPid(pid, arr, all) {
      if (pid && arr && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].id == pid) {
            this.subExpandedKeys.push(arr[i].id)
            this.getExpandKeysByPid(arr[i]['pid'], all, all)
          } else {
            this.getExpandKeysByPid(pid, arr[i].children, all)
          }
        }
      }
    },
    // 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
    loadDataByExpandedRows(dataList) {
      if (this.expandedRowKeys.length > 0) {
        return getAction(this.url.getChildListBatch, { parentIds: this.expandedRowKeys.join(',') }).then((res) => {
          if (res.success && res.result.records.length > 0) {
            //已展开的数据批量子节点
            let records = res.result.records
            const listMap = new Map()
            for (let item of records) {
              let pid = item[this.pidField]
              if (this.expandedRowKeys.join(',').includes(pid)) {
                let mapList = listMap.get(pid)
                if (mapList == null) {
                  mapList = []
                }
                mapList.push(item)
                listMap.set(pid, mapList)
              }
            }
            let childrenMap = listMap
            let fn = (list) => {
              if (list) {
                list.forEach((data) => {
                  if (this.expandedRowKeys.includes(data.id)) {
                    data.children = this.getDataByResult(childrenMap.get(data.id))
                    fn(data.children)
                  }
                })
              }
            }
            fn(dataList)
          }
        })
      } else {
        return Promise.resolve()
      }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      console.log(selectedRowKeys)
      console.log(selectionRows)
      this.$emit('change', selectedRowKeys[0],this.selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows

    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
